package araxy.blog.interceptor.exceptionhandler;

import org.apache.shiro.authc.*;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.HostUnauthorizedException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class ShiroExceptionHandler {

    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public Map<String,Object> authenticationExceptionHandler(AuthenticationException e) {
        Map<String,Object> map = new HashMap<>();
        map.put("flg",false);
        if (e instanceof IncorrectCredentialsException) {
            map.put("msg","账号或密码错误");
        } else if (e instanceof ExpiredCredentialsException){
            map.put("msg","凭证过期");
        } else if (e instanceof UnknownAccountException) {
            map.put("msg","账号不存在");
        } else if (e instanceof ExcessiveAttemptsException) {
            map.put("msg","登录太频繁，请稍后再试");
        } else if (e instanceof DisabledAccountException) {
            map.put("msg","账号被禁用");
        } else if (e instanceof LockedAccountException) {
            map.put("msg","账号被锁定");
        } else if (e instanceof ConcurrentAccessException) {
            map.put("msg","并发访问异常");
        } else if (e instanceof UnsupportedTokenException) {
            map.put("msg","token验证异常");
        }
        return map;
    }

    @ExceptionHandler(AuthorizationException.class)
    @ResponseBody
    public Map<String,Object> authenticationExceptionHandler(AuthorizationException e) {
        Map<String,Object> map = new HashMap<>();
        map.put("flg",false);
        if (e instanceof UnauthenticatedException) {
            map.put("msg","授权异常");
        } else if (e instanceof UnauthorizedException){
            map.put("msg","对不起，该账号无权访问");
        } else if (e instanceof HostUnauthorizedException) {
            map.put("msg","主机未经验证");
        }
        return map;
    }
}
